package com.fary.web.argument;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fary.exception.SystemException;
import org.springframework.core.MethodParameter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class RequestJsonMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestJson.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestJson requestJson = parameter.getParameterAnnotation(RequestJson.class);

        String name = (requestJson != null && StringUtils.hasLength(requestJson.name()) ? requestJson.name() : parameter.getParameterName());
        Assert.state(name != null, "Unresolvable parameter name");

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        Assert.state(request != null, "解析Json请求报文错误！");
        if (request.getAttribute("requestJson") == null) {
            ServletInputStream inputStream = request.getInputStream();
            List<String> strings = new ArrayList<>();
            IoUtil.readUtf8Lines(inputStream, strings);
            String join = String.join("", strings);
            try {
                JSONObject jsonObject = JSONUtil.parseObj(join);
                request.setAttribute("requestJson", jsonObject);
            } catch (Exception e) {
                throw new SystemException("请传json格式报文！");
            }
        }
        JSONObject jsonObject = (JSONObject) request.getAttribute("requestJson");
        Assert.state(jsonObject != null, "解析Json请求报文错误！");

        String arg = jsonObject.getStr(name);
        if (StrUtil.isBlank(arg) && requestJson != null && requestJson.required()) {
            throw new SystemException(requestJson.message());
        }
        if (int.class.isAssignableFrom(parameter.getParameterType())) {
            return Integer.parseInt(arg);
        }
        return arg;
    }

}
